package com.lonely.order.support.synchronizer.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lonely.common.exception.BusinessException;
import com.lonely.goods.enums.GoodsEnum;
import com.lonely.order.domain.dto.api.GetBigGoodsBomReqDTO;
import com.lonely.order.domain.dto.api.GetBigGoodsBomResDTO;
import com.lonely.order.domain.entity.SysOrder;
import com.lonely.order.domain.entity.SysOrderPart;
import com.lonely.order.service.IMesApiService;
import com.lonely.order.service.IOrderPartService;
import com.lonely.order.support.synchronizer.SynchronizerOrderContext;
import com.lonely.order.threadlocals.OrderSynchronizedThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author : 黄志标
 * @date: 2025/7/31 15:30
 * @description: 同步订单部件服务
 */
@Service
@Slf4j
public class SynchronizerOrderPartService {

    @Autowired
    private IMesApiService mesApiService;

    @Autowired
    private IOrderPartService orderPartService;

    @Autowired
    private SynchronizerOrderSecondProcessService synchronizerOrderSecondProcessService;

    @Autowired
    private SynchronizerOrderProcessService synchronizerOrderProcessService;

    @Autowired
    private SynchronizerOrderPartMaterialService synchronizerOrderPartMaterialService;

    /**
     * 基于物料数据创建物料部件信息
     *
     * @param synchronizerOrderContext
     * @return
     */
    private void createOrderPartMaterials(SynchronizerOrderContext synchronizerOrderContext) {
        SysOrder sysOrder = synchronizerOrderContext.getNewOrder();

        // 同步大货bom数据
        GetBigGoodsBomReqDTO reqDTO = new GetBigGoodsBomReqDTO();
        reqDTO.setProduceOrderId(Convert.toInt(sysOrder.getProduceOrderId()));
        GetBigGoodsBomResDTO bigGoodsBom = null;
        int count = 0;
        do {
            try {
                bigGoodsBom = this.mesApiService.getBigGoodsBom(synchronizerOrderContext.getOpenApiSecret(), reqDTO);
            } catch (Exception e) {
                if (count < 3) {
                    if (e.getMessage().contains("限流")) {
                        count++;
                        ThreadUtil.sleep(500);
                        continue;
                    }
                }
                throw e;
            }
            break;
        } while (true);

        if (CollUtil.isEmpty(Objects.requireNonNull(bigGoodsBom).getBigGoodsBom())) {
            return;
        }
        synchronizerOrderContext.setBigGoodsBom(bigGoodsBom);

        if (bigGoodsBom.getMultiPiecesQuantity() == 1) {
            // 单部件
            SysOrderPart sysOrderPart = buildInitDefaultOrderPart(sysOrder);
            sysOrderPart.setPartLibrary("默认部件");
            this.orderPartService.save(sysOrderPart);

            // 保存部件相关信息
            this.saveOrderPartOtherData(synchronizerOrderContext, sysOrderPart, StrUtil.EMPTY);
        } else {
            // 多部件
            List<String> partCodes = bigGoodsBom.getBigGoodsBom().stream().map(GetBigGoodsBomResDTO.BigGoodsBom::getPartCode).filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList());
            if (CollUtil.isEmpty(partCodes)) {
                return;
            }

            Set<String> existsAddPartCodes = new HashSet<>();
            bigGoodsBom.getBigGoodsBom().stream().filter(x -> StrUtil.isNotBlank(x.getPartCode())).forEach(x -> {
                if (existsAddPartCodes.contains(x.getPartCode())) {
                    // 已处理
                    return;
                }

                SysOrderPart sysOrderPart = buildInitDefaultOrderPart(sysOrder);
                sysOrderPart.setPartCode(x.getPartCode());
                sysOrderPart.setPartLibrary(x.getPartName());
                sysOrderPart.setType(GoodsEnum.GoodsPartTypeEnum.SUIT.getType());
                this.orderPartService.save(sysOrderPart);

                // 保存部件相关信息
                this.saveOrderPartOtherData(synchronizerOrderContext, sysOrderPart, x.getPartCode());

                existsAddPartCodes.add(x.getPartCode());
            });
        }

    }

    /**
     * 同步订单部件数据
     *
     * @param synchronizerOrderContext
     */
    public void synchronizerOrderPart(SynchronizerOrderContext synchronizerOrderContext) {
        try {
            // 判断是否已存在
            int count = this.orderPartService.count(new LambdaQueryWrapper<SysOrderPart>()
                    .eq(SysOrderPart::getProduceOrderId, synchronizerOrderContext.getProduceOrderId())
            );
            if (count > 0) {
                log.debug("同步订单号：{}对应的部件信息已存在,退出此次同步", synchronizerOrderContext.getProduceOrderId());
                return;
            }

            // 创建物料信息
            createOrderPartMaterials(synchronizerOrderContext);
        } catch (Exception e) {
            log.error("同步订单号：{}对应的部件信息失败", synchronizerOrderContext.getProduceOrderId(), e);
            throw new BusinessException(e.getMessage());
        }
    }


    /**
     * 保存部件相关信息
     *
     * @param synchronizerOrderContext
     * @param sysOrderPart
     * @param sheinPartCode
     */
    private void saveOrderPartOtherData(SynchronizerOrderContext synchronizerOrderContext, SysOrderPart sysOrderPart, String sheinPartCode) {
        // 保存物料部件物料信息
        this.synchronizerOrderPartMaterialService.synchronizerOrderPartMaterial(synchronizerOrderContext, sysOrderPart.getId(), sheinPartCode);

        // 保存部件二次工艺信息
        this.synchronizerOrderSecondProcessService.synchronizerOrderSecondProcess(synchronizerOrderContext, sysOrderPart, sheinPartCode);

        // 保存部件工序信息
        this.synchronizerOrderProcessService.synchronizerOrderProcess(synchronizerOrderContext, sysOrderPart, sheinPartCode);

    }


    /**
     * 构建默认的部件信息
     *
     * @param sysOrder
     * @return
     */
    private SysOrderPart buildInitDefaultOrderPart(SysOrder sysOrder) {
        SysOrderPart sysOrderPart = new SysOrderPart();
        sysOrderPart.setOrderId(sysOrder.getId());
        sysOrderPart.setProduceOrderId(Convert.toStr(sysOrder.getProduceOrderId()));
        sysOrderPart.setPartLibrary(null);
        sysOrderPart.setPartCode(StrUtil.EMPTY);
        sysOrderPart.setQuantity(0);
        sysOrderPart.setType(GoodsEnum.GoodsPartTypeEnum.NO_SUIT.getType());
        sysOrderPart.setCreateBy(OrderSynchronizedThreadLocal.getCreateBy());
        sysOrderPart.setUpdateBy(OrderSynchronizedThreadLocal.getCreateBy());
        return sysOrderPart;
    }


}
